import { outLogin } from '@/services/ant-design-pro/api';
import {LogoutOutlined, SettingOutlined} from '@ant-design/icons';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { history, useModel } from '@umijs/max';
import {message, Space, Spin} from 'antd';
import type { MenuInfo } from 'rc-menu/lib/interface';
import React, { useCallback } from 'react';
import HeaderDropdown from '../HeaderDropdown';

export type GlobalHeaderRightProps = {
  menu?: boolean;
  children?: React.ReactNode;
};

export const AvatarName = () => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  return <span className="anticon">{currentUser?.name}</span>;
};

export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({children }) => {
  /**
   * 退出登录，并且将当前的 url 保存
   */
  const loginOut = async () => {
   const res = await outLogin();
   if (res.status === "done") {

     // 退出成功
     message.success(res.message)

     // 清除本地数据
     localStorage.clear()

     // 跳转回登录页
     history.push("/login")
   }else {
     message.error(res.message)
   }

  };
  const actionClassName = useEmotionCss(({ token }) => {
    return {
      display: 'flex',
      height: '48px',
      marginLeft: 'auto',
      overflow: 'hidden',
      alignItems: 'center',
      padding: '0 8px',
      cursor: 'pointer',
      borderRadius: token.borderRadius,
      '&:hover': {
        backgroundColor: token.colorBgTextHover,
      },
    };
  });

  // 头部按钮CSS
  const spaceClassName = useEmotionCss(() => {
    return {
      display: 'flex',
      float: 'right',
      height: '48px',
      marginLeft: 'auto',
      overflow: 'hidden',
    };
  });
  //
  // // span按钮CSS
  // const spanClassName = useEmotionCss(() => {
  //   return {
  //     display: 'flex',
  //     alignItems: 'center',
  //     height: '48px',
  //     padding: '0 12px',
  //     cursor: "pointer",
  //     transition: "all 0.3s",
  //     '>span': {
  //       verticalAlign: "middle",
  //     },
  //   };
  // });


  const { initialState, setInitialState } = useModel('@@initialState');

  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      if (key === 'logout') {
        loginOut();
        return;
      }
      history.push(`/user/account/${key}`);
    },
    [setInitialState],
  );

  const loading = (
    <span className={actionClassName}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const { currentUser } = initialState;

  if (!currentUser || !currentUser.name) {
    return loading;
  }

  const menuItems = [
    // {
    //   key: 'notices',
    //   icon: <UserOutlined />,
    //   label: '消息中心',
    // },
    {
      key: 'settings',
      icon: <SettingOutlined />,
      label: '个人设置',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    },
  ];

  return (
    <>
      {/*<Space className={spaceClassName}>*/}
      {/*  <span*/}
      {/*    className={spanClassName}*/}
      {/*    onClick={() => {*/}
      {/*      history.push('/user/account/notices');*/}
      {/*    }}*/}
      {/*  >*/}
      {/*    <Badge*/}
      {/*      count={currentUser && currentUser.unreadCount}*/}
      {/*      size={'small'}*/}
      {/*      offset={[6, 0]}*/}
      {/*      overflowCount={99}*/}
      {/*      style={{ borderColor: '#f50' }}*/}
      {/*    >*/}
      {/*      <BellOutlined />*/}
      {/*    </Badge>*/}
      {/*  </span>*/}
      {/*</Space>*/}
      <Space className={spaceClassName}>
        <HeaderDropdown
          menu={{
            selectedKeys: [],
            onClick: onMenuClick,
            items: menuItems,
          }}
        >
          {children}
        </HeaderDropdown>
      </Space>
    </>
  );
};
